﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace MapEngine
{
    public class Camera
    {
        #region -- Atributos --
        private Vector2 Location = Vector2.Zero;
        private Vector2 MinLoc = Vector2.Zero;
        private Vector2 MaxLoc = Vector2.Zero;
        private Vector2 ViewportCenter = Vector2.Zero;
        #endregion


        #region -- Constructores --
        public Camera(Point viewportSize)
            : this(Vector2.Zero, viewportSize)
        { }


        public Camera(Vector2 loc, Point viewportSize)
        {
            Location = loc;
            resetViewport(viewportSize);
          }
        #endregion



        #region -- Viewport --
        void resetViewport(Point viewportSize)
        {
            this.ViewportCenter.X = viewportSize.X / 2;
            this.ViewportCenter.Y = viewportSize.Y / 2;
            this.MinLoc = this.ViewportCenter;
            this.MaxLoc.X = (MapConfig.MapSize.X * MapConfig.TileSize.X) - this.ViewportCenter.X;
            this.MaxLoc.Y = (MapConfig.MapSize.Y * MapConfig.TileSize.Y) - this.ViewportCenter.Y;
            Location.X = AuxFunctions.clamp(Location.X, MinLoc.X, MaxLoc.X);
            Location.Y = AuxFunctions.clamp(Location.Y, MinLoc.Y, MaxLoc.Y);
        }
        #endregion



        #region -- Movimiento de la cámara --
        public Vector2 getLocation()
        {
            return Location;
        }


        public void setLocationInPixels(Vector2 loc)
        {
            Location.X = AuxFunctions.clamp(loc.X, MinLoc.X, MaxLoc.X);
            Location.Y = AuxFunctions.clamp(loc.Y, MinLoc.Y, MaxLoc.Y);
        }


        public void setLocationInTiles(Vector2 loc)
        {
            Location.X = AuxFunctions.clamp(loc.X * MapConfig.TileSize.X, MinLoc.X, MaxLoc.X);
            Location.Y = AuxFunctions.clamp(loc.Y * MapConfig.TileSize.Y, MinLoc.Y, MaxLoc.Y);
        }
        #endregion



        #region -- Funciones de visualización --
        public Matrix computeViewMatrix()
        {
            return Matrix.CreateTranslation(ViewportCenter.X - Location.X, ViewportCenter.Y - Location.Y, 0.0f);
        }


        public Range2D computeViewRange()
        {
            Range2D range;
            range.firstX = (int)(Location.X - ViewportCenter.X) / MapConfig.TileSize.X;
            range.firstY = (int)(Location.Y - ViewportCenter.Y) / MapConfig.TileSize.Y;

            range.lastX = (int)(Location.X + ViewportCenter.X) / MapConfig.TileSize.X;
            range.lastY = (int)(Location.Y + ViewportCenter.Y) / MapConfig.TileSize.Y;
            return range;
        }
        #endregion
    }
}
